package cn.dlc.com.service.impl;

import cn.dlc.com.dao.UserDao;
import cn.dlc.com.domain.SysRole;
import cn.dlc.com.domain.SysUser;
import cn.dlc.com.service.RoleService;
import cn.dlc.com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleService roleService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public void save(SysUser user) {

        if(user != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userDao.save(user);
    }

    @Override
    public List<SysUser> findAll() {
        return userDao.findAll();
    }

    @Override
    public Map<String, Object> toAddRolePage(Integer id) {
        List<SysRole> allRoles = roleService.findAll();
        List<Integer> myRoles = userDao.findRolesByUid(id);
        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", allRoles);
        map.put("myRoles", myRoles);
        return map;
    }

    @Override
    public void addRoleToUser(Integer userId, Integer[] ids) {
        userDao.removeRoles(userId);
        for (Integer rid : ids) {
            userDao.addRoles(userId, rid);
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        try{
            // 获取到数据库里面的用户对戏
            SysUser sys = userDao.findByName(username);
            //
            if(sys == null) {
                return null;
            }
            // 不为空，找得到
            // 权限部分 GrantedAuthority 的子类
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            // 获取到用户的权限
            List<SysRole> roles = sys.getRoles();
            if(roles != null && roles.size() > 0) {
                for (SysRole role : roles) {
                    // 添加权限
                    authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
                }
            }

            // 1.1 进行用户的校验，（明码校验）
            // UserDetails user = new User(username, "{noop}" + sys.getPassword(), authorities);
            // 1.2 配置 BCryptPasswordEncoder 之后不需要再使用明码
            // UserDetails user = new User(username, sys.getPassword(), authorities);
            // 1.3 整合权限
            UserDetails user = new User(username, sys.getPassword(),
                    sys.getStatus() == 1,
                    true,
                    true,
                    true,
                    authorities);

            return user;

        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }
}
